package com.sq.futuralwakeupwordsdk;

import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSONObject;
import com.blankj.utilcode.util.SPUtils;
import com.jack.serialportlib.SerialPortMicHelper;
import com.sq.futuralwakeupwordsdk.databinding.ActivityWakeupWordBinding;
import com.sq.futuralwakeupwordsdk.utils.DialogUtils;

import java.lang.ref.WeakReference;
import java.nio.charset.StandardCharsets;
import java.util.Formatter;

public class WakeupWordActivity extends BaseActivity {
    private final String TAG = WakeupWordActivity.class.getSimpleName();
    private ActivityWakeupWordBinding uiBinding;
    String syncHead = "A5"; //同步头
    String userId = "01";   //用户id
    String msgType = "05";  //消息类型
    String msgLen = "5d00"; //消息长度
    String msgId = "0200";  //消息id
    Dialog dialog;

    protected static final int SET_WAKEUP_WORD_DONE = 100;
    protected static MyHandler handler;
    static class MyHandler extends Handler {
        private WeakReference<WakeupWordActivity> reference;

        public MyHandler(WakeupWordActivity activity) {
            this.reference = new WeakReference<WakeupWordActivity>(activity);
        }

        public WakeupWordActivity getActivity() {
            return reference.get();
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SET_WAKEUP_WORD_DONE:
                    handler.getActivity().dismissWaitDlg();
                    handler.getActivity().showMyToast(R.string.setting_wakeup_word_done, Toast.LENGTH_LONG);
                    break;
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new MyHandler(this);
        uiBinding = DataBindingUtil.setContentView(this, R.layout.activity_wakeup_word);
        uiBinding.setHandler(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        handler.removeCallbacksAndMessages(null);
    }

    public void wakeupSetting() {
        String wakeupWord = uiBinding.wakeupWordEt.getText().toString().trim();
        String threshold = uiBinding.thresholdEt.getText().toString().trim();
        if (TextUtils.isEmpty(wakeupWord) || TextUtils.isEmpty(threshold)) {
            showMyToast(R.string.input_error, Toast.LENGTH_SHORT);
        } else {
            JSONObject wakeupWordAndThreshold = new JSONObject();
            wakeupWordAndThreshold.put("keyword", wakeupWord);  //"xiao3 qing2 xiao3 qing2"
            wakeupWordAndThreshold.put("threshold", threshold); //"200"

            JSONObject all = new JSONObject();
            all.put("type", "wakeup_keywords");
            all.put("content", wakeupWordAndThreshold);

            String msgData = stringToHex(all.toString());
            Log.e(TAG, "wakeupWord：" + msgData);

            msgLen = lenToHex(msgData.length()/2);
            Log.e(TAG, "msgLen: " + msgLen);

            String res = syncHead + userId + msgType + msgLen + msgId + msgData;
            String allData = res + calculateLRC(res);
            Log.e(TAG, "all data: " + allData);

            handler.sendEmptyMessageDelayed(SET_WAKEUP_WORD_DONE, 30*1000);
            dialog = DialogUtils.showWaitDlg(this, R.string.hint, R.string.setting_wakeup_word);
            SerialPortMicHelper.getInstance().sendHex(allData);
        }
    }

    private String lenToHex(int len) {
        String res = Integer.toHexString(len);
        return res.length()%2 == 1 ? "0" + res + "00" : res + "00";
    }

    public String stringToHex(String input) {
        byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
        StringBuilder hexString = new StringBuilder();
        Formatter formatter = new Formatter(hexString);
        for (byte b : bytes) {
            formatter.format("%02x", b);
        }
        formatter.close();
        return hexString.toString();
    }

    //除校检码字节外所有字节求和取反并加1
    public static String calculateLRC(String hexString) {
        byte[] bytes = new byte[hexString.length() / 2];
        for (int i = 0; i < hexString.length(); i += 2) {
            String subStr = hexString.substring(i, i + 2);
            bytes[i / 2] = (byte) Integer.parseInt(subStr, 16);
        }

        byte lrc = 0;
        for (byte b : bytes) {
            lrc += b;
        }

        return String.format("%02x", (byte)(~lrc+1));
    }

    public void dismissWaitDlg() {
        if (dialog != null) {
            dialog.dismiss();
            dialog = null;
        }
    }
}